using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using VM.Common.DataUntil;

using VM.Common.Result;
using VM.Entity.EntityDto.common;
using VM.Entity.EntityDto.Member;
using VM.Entity.EntityMap.Member;
using VM.IBLL.Member;
using VM.WebAPI.Controllers;
using VM.WebCore.Jwt;
using VM.WebCore.SwaggerExtend;
using VM.Wechat;

namespace WeatherForecastTest.Controllers
{
    /// <summary>
    ///会员相关操作类 PC+PHONE
    /// </summary>
    [ApiController]
    [Route("api/member")]
    public class MemberController : ControllerBase
    {
        private readonly IMemberBLL _IMemberBLL;
        private readonly IJWTService _IJWTService;
        private readonly IHttpContextAccessor _HttpContextAccessor;

   
        



        public MemberController(IJWTService iJWTService, IMemberBLL iMemberBLL, IHttpContextAccessor httpContextAccessor)
        {

            _IMemberBLL = iMemberBLL;
            _IJWTService = iJWTService;
            _HttpContextAccessor = httpContextAccessor;
  
        }
        /// <summary>
        ///校验当前用户是否已存在   PHONE
        /// </summary>
        /// <param name="checkType">1 验证手机号是否存在  2验证微信OpenId是否存在</param>
        /// <param name="phone"></param>
        /// <param name="wxOpenId"></param>
        /// <returns></returns>
        [HttpGet]
        //[Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("checkMemberIsExit")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public ApiResult checkMemberIsExit(int checkType,string? phone,string? wxOpenId)
        {
            ApiResult Res = new ApiResult() { 
            code=403,
            msg= "传入类型错误（checkType）"
            };
            if (checkType == 1)
            {
                //校验验证码是否可用，如果可用，返回true
                 Res = _IMemberBLL.CheckMemberIsExit(checkType, phone);
            }
            else if (checkType == 2) {
                 Res = _IMemberBLL.CheckMemberIsExit(checkType, wxOpenId);

            }

            return Res;
        }

        [HttpGet]
        //[Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("getMemberInfoByPhone")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public ApiDataResult<sys_member> getMemberInfoByPhone( string phone)
        {

            //校验验证码是否可用，如果可用，返回true
            ApiDataResult<sys_member> Res = _IMemberBLL.getMemberInfoByUniqStr(1,phone);
            return Res;
        }


        [HttpGet]
        //[Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("getMemberInfoByWxOPenId")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public ApiDataResult<sys_member> getMemberInfoByWxOPenId(string wxOpenId)
        {

            //校验验证码是否可用，如果可用，返回true
            ApiDataResult<sys_member> Res = _IMemberBLL.getMemberInfoByUniqStr(2,wxOpenId);
            return Res;
        }


        /// <summary>
        /// 登录验证 PHONE
        /// </summary>
        /// <param name="sys_member">登录信息</param>
        /// <returns></returns>
        [HttpPost]
        //[Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("memberLogin")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public async Task<ApiDataResult<MemberLoginResMap>> memberLogin(MemberLoginMap obj)
        {

            ApiDataResult<MemberLoginResMap> res = new ApiDataResult<MemberLoginResMap>();


            int expiresIn = 0 ;
            string tokenType = "Bearer";
            //判断登录类型  1 账号密码  2验证码 3本机号码一键登录 4微信openid一键登录

            if (obj.loginType == 4)
            {
                //判断当前手机号是否已存在，如果已存在，则直接登录，如果不存在，则创建新用户。
                if (obj.isExit != 1)
                {

                    //获取当前时间戳
                    string Str = Timestamp.getNowTimeStamp().ToString() + RandomNo.GetRandomNo6().ToString();
                    string md5pwd = PwdPro.GeneratePwdStr(RandomNo.GetRandomNo8());
                    QRCodeInfo QrObj = new QRCodeInfo() {
                    type="user",
                    qrInfo=Str
                    };

                    string QRCodePath = "";/*QRCoderPro.RenderQrCode( JsonConvert.SerializeObject(QrObj), "FilesQRCode");*/

                    sys_member mem = new sys_member();
                    mem.avatar = "/UploadImg/header.jpg";
                    mem.isVip = 0;
                    mem.nickName = "xhNike_" + Str;
                    mem.name = "xh_" + Str;
                    mem.createDatetime = DateTime.Now; ;
                    mem.createUserId = 0;
                    mem.pwd = md5pwd;
                    mem.qrCodeImgUrl= QRCodePath;
                    mem.qrCodeInfo = Str;
                    mem.registerType = 4;
                    mem.userType = 1;
                    mem.isWalletPwd = 0;
                    mem.countryRegion = 86;
                    mem.wxOpenId = obj.wxOpenId;


                    ApiDataResult<sys_member> RegisterRes = memberRegister(mem);
                    if (RegisterRes.code == 200) //注册成功
                    {
                        //获取到保存到数据库的userid
                        int MemberId = (int)RegisterRes.data.id;
                        //将UserId进行AES加密
                        string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                        JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey); //RefreshJwtTokenAsync
                        if (jo.code == 200)
                        {
                            //后端一键登录
                            res = _IMemberBLL.MemberSSOLogin(obj);
                            if (res.code == 200)
                            {
                                string accessToken = jo.token;
                                string refreshToken = jo.refreshtoken;
                                res.msg = "登录成功";
                                res.data.access_token = accessToken;
                                res.data.refresh_token = refreshToken;
                                res.data.token_type = tokenType;
                                //解析获取到的token
                                res.data.id = _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp");
                                res.data.nbf = _IJWTService.AnaliseToken(res.data.access_token, "nbf");
                                return res;
                            }
                            else
                            {
                                return res;
                            }
                        }
                        else
                        {

                            return new ApiDataResult<MemberLoginResMap>
                            {
                                code = jo.code,
                                msg = jo.msg,
                                data = null

                            }; 

                        }
                    }
                    else
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = RegisterRes.code,
                            msg = RegisterRes.msg,
                            data = null

                        };

                    }
                }
                //已存在微信公众信息
                else
                {
                    //先获取用户信息
                    ApiDataResult<sys_member> memberInfo = getMemberInfoByWxOPenId(obj.wxOpenId);


                    if (memberInfo.code == 200)
                    {

                        //后端鉴权登录
                        res = _IMemberBLL.MemberSSOLogin(obj);
                        if (res.code == 200)
                        {
                            //获取到保存到数据库的userid
                            int MemberId = (int)memberInfo.data.id;
                            //将UserId进行AES加密
                            string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                            JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey);
                            string accessToken = jo.token;
                            string refreshToken = jo.refreshtoken;
                            if (jo.code == 200)
                            {
                                res.msg = "登录成功";
                                res.data.access_token = accessToken;
                                res.data.refresh_token = refreshToken;
                                res.data.token_type = tokenType;

                                res.data.id = _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp");
                                res.data.nbf = _IJWTService.AnaliseToken(res.data.access_token, "nbf");
                                return res;
                            }
                            else
                            {
                                return res;
                            }
                        }
                        else
                        {

                            res.msg = "统一鉴权失败";
                            res.code = 403;
                            res.data = null;

                            return res;

                        }

                    }
                    else
                    {
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 411,
                            msg = "错误：" + memberInfo.msg,
                            data = null

                        };

                    }
                }

            }
            if (obj.loginType == 3)
            {
                //判断当前手机号是否已存在，如果已存在，则直接登录，如果不存在，则创建新用户。
                if (obj.isExit != 1)
                {

                    //获取当前时间戳
                    string Str = Timestamp.getNowTimeStamp().ToString() + RandomNo.GetRandomNo6().ToString();
                    string md5pwd = PwdPro.GeneratePwdStr(RandomNo.GetRandomNo8());
                    sys_member mem = new sys_member();
                    mem.avatar = "/UploadImg/header.jpg";
                    mem.isVip = 0;
                    mem.nickName = "xhNike_" + Str;
                    mem.name = "xh_" + Str;
                    mem.createDatetime = DateTime.Now; ;
                    mem.createUserId = 0;
                    mem.pwd = md5pwd;
                    mem.phone = obj.phone;
                    mem.registerType = 3;
                    mem.userType = 1;
                    mem.isWalletPwd = 0;
                    mem.countryRegion = 86;
             
              
                    ApiDataResult<sys_member> RegisterRes = memberRegister(mem);
                    if (RegisterRes.code == 200) //注册成功
                    {
                        //获取到保存到数据库的userid
                        int MemberId = (int)RegisterRes.data.id;
                        //将UserId进行AES加密
                        string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                        JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId,obj.PublicKey,obj.PrivateKey); //RefreshJwtTokenAsync
                        if (jo.code == 200)
                        {
                            //后端一键登录
                            res = _IMemberBLL.MemberSSOLogin(obj);
                            if (res.code == 200)
                            {
                                string accessToken = jo.token;
                                string refreshToken = jo.refreshtoken;
                                res.msg = "登录成功";
                                res.data.access_token = accessToken;
                                res.data.refresh_token = refreshToken;
                                res.data.token_type = tokenType;
                                //解析获取到的token
                               res.data.id= _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp");
                                res.data.nbf = _IJWTService.AnaliseToken(res.data.access_token, "nbf");
                                return res;
                            }
                            else
                            {
                                return res;
                            }
                        }
                        else
                        {

                            return res;

                        }
                    }
                    else
                    {
                        
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = RegisterRes.code,
                            msg = RegisterRes.msg,
                            data = null

                        };

                    }
                }
                //已存在手机号
                else
                {
                    //先获取用户信息
                    ApiDataResult<sys_member> memberInfo = getMemberInfoByPhone(obj.phone);
                    
                    
                    if (memberInfo.code == 200)
                    {

                        //后端鉴权登录
                      res = _IMemberBLL.MemberSSOLogin(obj);
                        if (res.code == 200)
                        {
                            //获取到保存到数据库的userid
                            int MemberId = (int)memberInfo.data.id;
                            //将UserId进行AES加密
                            string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                            JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey);
                            string accessToken = jo.token;
                            string refreshToken = jo.refreshtoken;
                            if (jo.code == 200)
                            {
                                res.msg = "登录成功";
                                res.data.access_token = accessToken;
                                res.data.refresh_token =refreshToken;
                                res.data.token_type = tokenType;
                      
                                res.data.id = _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp");
                                res.data.nbf = _IJWTService.AnaliseToken(res.data.access_token, "nbf");
                                return res;
                            }
                            else
                            {
                                return res;
                            }
                        }
                        else
                        {

                            res.msg = "统一鉴权失败";
                            res.code = 403;
                            res.data = null;
                            
                            return res;

                        }

                    }
                    else
                    {
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 411,
                            msg = "错误："+memberInfo.msg,
                            data = null

                        };

                    }
                }

            }
            //短信验证码登录
            else if (obj.loginType == 2)
            {
                if (obj.isExit != 1)
                {

                    //获取当前时间戳
                    string Str = Timestamp.getNowTimeStamp().ToString() + RandomNo.GetRandomNo6().ToString();
                    string md5pwd = PwdPro.GeneratePwdStr(RandomNo.GetRandomNo8());
                    sys_member mem = new sys_member();
                    mem.avatar = "/UploadImg/header.jpg";
                    mem.isVip = 0;
                    mem.nickName = "xhNike_" + Str;
                    mem.name = "xh_" + Str;
                    mem.createDatetime = DateTime.Now; ;
                    mem.createUserId = 0;
                    mem.pwd = md5pwd;
                    mem.phone = obj.phone;
                    mem.registerType = 2;
                    mem.userType = 1;
                    mem.isWalletPwd = 0;
                    mem.countryRegion = 86;

                    ApiDataResult<sys_member> RegisterRes = memberRegister(mem);
                    if (RegisterRes.code == 200) //注册成功
                    {
                        //获取到保存到数据库的userid
                        int MemberId = (int)RegisterRes.data.id;
                        //将UserId进行AES加密
                        string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                        //短信验证码登录成功
                        res = _IMemberBLL.MemberMsgLogin(obj);// _IMemberBLL.MemberSSOLogin(sys_member);
                        if (res.code == 200)
                        {
                            JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey);
                            if (jo.code == 200)
                            {
                                res.msg = "登录成功";
                                res.data.access_token = jo.token;
                                res.data.refresh_token = jo.refreshtoken;
                                res.data.token_type = tokenType;
                                res.data.id = _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp");
                                res.data.nbf = _IJWTService.AnaliseToken(res.data.access_token, "nbf");
                     
                                 
                                ;
                                return res;
                            }
                            else
                            {
                                return new ApiDataResult<MemberLoginResMap>
                                {
                                    code = 411,
                                    msg = "统一鉴权时失败",
                                    data = null
                                };

                            }
                        }
                        else
                        {
                            return res;

                        }
                    }
                    else
                    {
                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = RegisterRes.code,
                            msg = RegisterRes.msg,
                            data = null

                        };

                    }
                }
                else
                {
                    //先获取用户信息
                    ApiDataResult<sys_member> memberInfo = getMemberInfoByPhone(obj.phone);
                    if (memberInfo.code == 200)
                    {
                        //获取到保存到数据库的userid
                        int MemberId = (int)memberInfo.data.id;
                        //将UserId进行AES加密
                        string AESUserId = AESUntil.Encrypt(MemberId.ToString());

                        res = _IMemberBLL.MemberMsgLogin(obj);// _IMemberBLL.MemberSSOLogin(sys_member);
                        if (res.code == 200)
                        {
                            JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey);
                            if (jo.code == 200)
                            {

                                res.msg = "登录成功";
                                res.data.access_token = jo.token;
                                res.data.token_type = tokenType;
                                res.data.refresh_token = jo.refreshtoken;
                                res.data.id = _IJWTService.AnaliseToken(res.data.access_token, "id");
                                res.data.exp = _IJWTService.AnaliseToken(res.data.access_token, "exp"); 
                                res.data.nbf= _IJWTService.AnaliseToken(res.data.access_token, "nbf");

                                return res;
                            }
                            else
                            {
                                return new ApiDataResult<MemberLoginResMap>
                                {
                                    code = 411,
                                    msg = "统一鉴权时失败",
                                    data = null

                                };
                            }
                        }
                        else
                        {
                            return res;
                        }
                    }
                    else
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 411,
                            msg = "会员信息不存在，检查传参",
                            data = null

                        };
                    }
                }
            }
            else if (obj.loginType == 1)
            {
                ApiDataResult<sys_member> MemberInfo = _IMemberBLL.MemberPwdLogin(obj);
                if (MemberInfo.code == 200)
                {
                    //获取到保存到数据库的userid
                    int MemberId = (int)MemberInfo.data.id;
                    //将UserId进行AES加密
                    string AESUserId = AESUntil.Encrypt(MemberId.ToString());
                    JsonObject jo = await OAuthController.GetJwtTokenAsync(AESUserId, obj.PublicKey, obj.PrivateKey);
                    if (jo.code == 200)
                    {
                        MemberLoginResMap data = new MemberLoginResMap()
                        {
                            access_token = jo.token,
                            token_type = tokenType,
                            refresh_token = jo.refreshtoken,
                            id = _IJWTService.AnaliseToken(jo.token, "id"),
                            exp = _IJWTService.AnaliseToken(jo.token, "exp"),
                            nbf = _IJWTService.AnaliseToken(jo.token, "nbf"),

                    };
                        res.code = 200;
                        res.msg = "登录成功";
                        res.data = data;

                        return res;
                    }
                    else
                    {

                        return new ApiDataResult<MemberLoginResMap>
                        {
                            code = 411,
                            msg = "统一鉴权时失败",
                            data = null
                        };
                    }
                }
                else
                {
                    return new ApiDataResult<MemberLoginResMap>
                    {
                            code = 403,
                            msg = "错误："+MemberInfo.msg,
                            data = null

                   }; 

                }

            }
            else
            {

                return new ApiDataResult<MemberLoginResMap>
                {
                    code = 401,
                    msg = "登录类型传参错误",
                    data = null

                };

            }

        }

        /// <summary>
        /// 用户注册 PHONE
        /// </summary>
        /// <param name="sys_member"></param>
        /// <returns></returns>
        [HttpPost]
        //[Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("memberRegister")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public ApiDataResult<sys_member> memberRegister(sys_member obj)
        {
            ApiResult checkRes = new ApiResult();
            if (obj.registerType == 3) {
                checkRes = checkMemberIsExit(1, obj.phone,"");
            }
            if (obj.registerType == 4)
            {
                checkRes = checkMemberIsExit(2,"",obj.wxOpenId);
            }

            //判断用户是否已注册

            if (checkRes.code == 200|| checkRes.code==411)
            {
                return new ApiDataResult<sys_member>
                {
                    code = 403,
                    msg = "用户已存在，请直接登录",
                    data = null

                };

            }
            else
            {

                sys_member Res = _IMemberBLL.MemberRegister(obj);
                if (Convert.ToInt32(Res.id) > 0)
                {
                    return new ApiDataResult<sys_member>
                    {
                        code = 200,
                        msg = "注册成功",
                        data = Res

                    };
                }
                else
                {
                    return new ApiDataResult<sys_member>
                    {
                        code = 403,
                        msg = "注册失败",
                        data = null
                    }
                       ;
                }
            }


        }


        /// <summary>
        /// 获取用户信息 PHONE
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("getMemberInfo")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public ApiDataResult<MemberInfoDto> getMemberInfo()
        {
            try
            {
                
                //获取到header 内的用户信息进行解析
                var authorizationHeader = _HttpContextAccessor.HttpContext.Request.Headers["Authorization"];
                //解析jwt
                string tokenInfo = authorizationHeader.ToString().Replace("bearer ", "").Replace("Bearer ", "");
                var AESId = _IJWTService.AnaliseToken(tokenInfo, "id");
                //解析userid
                string memberId = AESUntil.Decrypt(AESId);
                //校验验证码是否可用，如果可用，返回true
                ApiDataResult<MemberInfoDto> Res = _IMemberBLL.GetMemberInfoByMemberId(Convert.ToInt32(memberId));
                return Res;
            }
            catch (Exception e) {

                return new ApiDataResult<MemberInfoDto>
                {
                    code = 403,
                    msg = "错误：" + e.Message+";有可能是bearer内解析id值出错",
                    data = null 
                };
            }
        }

        /// <summary>
        /// 修改用户信息，异步接口  PHONE
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]//要求通过授权才行---只要能鉴权成功，都能通过]
        [Route("updateMember")]
        [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
        public async Task<ApiResult> updateMember(sys_member obj)
        {

            //判断用户是否已注册
            //获取到header 内的用户信息进行解析
            var authorizationHeader = _HttpContextAccessor.HttpContext.Request.Headers["Authorization"];
            //解析jwt
            string tokenInfo = authorizationHeader.ToString().Replace("bearer ", "").Replace("Bearer ", "");
            var AESId = _IJWTService.AnaliseToken(tokenInfo, "id");
            //解析userid
            string memberId = AESUntil.Decrypt(AESId);
            obj.id =Convert.ToInt32( memberId);
            //校验验证码是否可用，如果可用，返回true
            bool b =await  _IMemberBLL.updateMemberNameById(Convert.ToInt32(memberId),obj);
            if (b == true)
            {
                return new ApiResult
                {
                    code = 201,
                    msg = "修改成功" 
                };
            }
            else
            {
                return new ApiResult
                {
                    code = 403,
                    msg = "修改失败"
                };
            }
        }





      
         


    }
}